<template>
  <div class="m-select" :class="{'is-disabled': disabled}" @click="handleClick">
    <span class="m-select-text" :data-placeholder="placeholder">{{getLabel()}}</span>
    <div class="m-select-options">
      {{value}}
      <slot></slot>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import SelectMenu from './SelectMenu'
export default {
  componentName: 'MSelect',
  props: {
    placeholder: {
      type: String,
      default: '请选择'
    },
    value: {
      type: [String, Number, Array]
    },
    max: {
      type: Number,
      default: 1
    },
    disabled: {
      type: Boolean
    }
  },
  methods: {
    getLabel () {
      let result = this.getOptions().filter(item => {
        if (this.max === 1) {
          return item.value === this.value
        } else {
          return this.value.indexOf(item.value) > -1
        }
      })
      return result.map(item => item.label).join(',')
    },
    handleClick () {
      if (!this.disabled) {
        let options = this.getOptions()
        let self = this
        let node = document.createElement('div')
        document.body.appendChild(node)
        this.$popup = new Vue({
          el: node,
          data () {
            return {
              value: self.max === 1 ? [self.value] : self.value
            }
          },
          updated () {
            if (this.$$toClose) {
              setTimeout(self.handleClose, 32)
            }
          },
          destroyed () {
            this.$el && this.$el.parentNode && this.$el.parentNode.removeChild(this.$el)
          },
          render (h) {
            return <SelectMenu options={options} value={this.value} onChange={this.handleChange} onClose={self.handleClose}/>
          },
          methods: {
            handleChange (value) {
              this.value = value
              let val = value
              if (self.max === 1) {
                val = value[0]
              }
              self.myValue = val
              self.$emit('input', val).$emit('change', val)
              this.$$toClose = true
            }
          }
        })
      }
    },
    handleClose () {
      this.$popup && this.$popup.$destroy()
    },
    getOptions () {
      return this.$children.map((item) => {
        let html = item.$el.innerHTML
        return {
          value: item.value,
          disabled: item.disabled,
          label: item.label || html,
          html: html
        }
      })
    }
  }
}
</script>

<style lang="scss">
  .m-select{
    display:inline-block;
    &-options{
      display:none;
    }
    &-text{
      @include placeholder;
    }
    &.is-disabled{
      opacity:0.6;
      pointer-events: none;
    }
  }
</style>
